<?php

namespace app\admin\controller\user;

use app\common\controller\Backend;
use app\common\model\Category;
use app\common\model\UserQualifications;
use Exception;
use fast\Tree;
use think\Db;
use think\exception\PDOException;
use think\exception\ValidateException;

/**
 * 用户个人信息管理
 *
 * @icon fa fa-circle-o
 */
class UserInfo extends Backend
{

    /**
     * UserInfo模型对象
     * @var \app\admin\model\user\UserInfo
     */
    protected $model = null;
    protected $categorylist = [];

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\user\UserInfo;
        $tree = Tree::instance();
        // todo 课题
        $tree->init(collection(Category::instance()->where(['type' => 'problem'])->order('createtime DESC')->select())->toArray(), 'pid');
        $this->categorylist = $tree->getTreeList($tree->getTreeArray(0), 'name');
        $problem = [null => ['type' => 'all', 'name' => __('None')]];
        foreach ($this->categorylist as $k => $v) {
            $problem[$v['id']] = $v;
        }
        // todo 行业
        $tree->init(collection(Category::instance()->where(['type' => 'sector'])->order('createtime DESC')->select())->toArray(), 'pid');
        $this->categorylist = $tree->getTreeList($tree->getTreeArray(0), 'name');
        $industry = [null => ['type' => 'all', 'name' => __('None')]];
        foreach ($this->categorylist as $key => $val) {
            $industry[$val['id']] = $val;
        }
        // todo 资质
        $tree->init(collection(Category::instance()->where(['type' => 'qualifications'])->order('createtime DESC')->select())->toArray(), 'pid');
        $this->categorylist = $tree->getTreeList($tree->getTreeArray(0), 'name');
        $qualifications = [null => ['type' => 'all', 'name' => __('None')]];
        foreach ($this->categorylist as $key => $val) {
            $qualifications[$val['id']] = $val;
        }
        $this->assign([
            'topic' => $problem,
            'industry' => $industry,
            'qualifications' => $qualifications
        ]);
    }



    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */


    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $list = $this->model
                ->with(['user'])
                ->where($where)
                ->order($sort, $order)
                ->paginate($limit);

            foreach ($list as $row) {


            }

            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }


    /**
     * 添加
     */
    public function add()
    {
        if (false === $this->request->isPost()) {
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);

        if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
            $params[$this->dataLimitField] = $this->auth->id;
        }
        $file = explode('/', $params['enclosure']);
        $params['topic'] = trim($params['topic']);
        $params['industry'] = trim($params['industry']);
        $params['enclosure_name'] = end($file);
        $params['city'] = implode(',', explode('/', $params['city']));
        if ($problem = Category::instance()->get(['type' => 'problem', 'id' => $params['topic']])) {
            $params['topic'] = $problem['name'];
        }
        if ($industry = Category::instance()->get(['type' => 'sector', 'id' => $params['industry']])) {
            $params['industry'] = $industry['name'];
        }
        // todo 检测相同用身份是否存在
        if ($this->model->get(['user_id' => $params['user_id']])) {
            $this->error('该关联用户已存在线上资料');
        }
        if ($this->model->get(['mobile' => $params['mobile']])) {
            $this->error('该用户手机号已存在');
        }
        if ($this->model->get(['wechat_number' => $params['wechat_number']])) {
            $this->error('该用户微信号已存在');
        }
        if ($this->model->get(['name' => $params['name'], 'id_cards' => $params['id_cards']])) {
            $this->error('该用户已存在');
        }
        $result = false;
        Db::startTrans();
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                $this->model->validateFailException()->validate($validate);
            }
            $result = $this->model->allowField(true)->save($params);
            // todo 新增时并更新User表信息
            if ($user = \app\common\model\User::instance()->get(['id' => $params['user_id']])) {
                $user->allowField(true)->save(['nickname' => $params['nickname']]);
            }
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($result === false) {
            $this->error(__('No rows were inserted'));
        }
        $this->success();
    }

    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds) && !in_array($row[$this->dataLimitField], $adminIds)) {
            $this->error(__('You have no permission'));
        }
        if (false === $this->request->isPost()) {
            $row['city'] = implode('/', explode(',', $row['city']));
            if ($problem = Category::instance()->get(['type' => 'problem', 'name' => $row['topic']])) {
                $row['topic'] = $problem['id'];
            }
            if ($industry = Category::instance()->get(['type' => 'sector', 'name' => $row['industry']])) {
                $row['industry'] = $industry['id'];
            }
            $this->view->assign('row', $row);
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);
        // todo 检测相同用身份是否存在
        if ($this->model->get(['user_id' => $params['user_id'], 'id' => ['<>', $ids]])) {
            $this->error('该关联用户已存在线上资料');
        }
        if ($this->model->get(['mobile' => $params['mobile'], 'id' => ['<>', $ids]])) {
            $this->error('该用户手机号已存在');
        }
        if ($this->model->get(['wechat_number' => $params['wechat_number'], 'id' => ['<>', $ids]])) {
            $this->error('该用户微信号已存在');
        }
        if ($this->model->get(['name' => $params['name'], 'id_cards' => $params['id_cards'], 'id' => ['<>', $ids]])) {
            $this->error('该用户已存在');
        }
        $file = explode('/', $params['enclosure']);
        $params['topic'] = trim($params['topic']);
        $params['industry'] = trim($params['industry']);
        $params['enclosure_name'] = end($file);
        $params['city'] = implode(',', explode('/', $params['city']));
        if ($problem = Category::instance()->get(['type' => 'problem', 'id' => $params['topic']])) {
            $params['topic'] = $problem['name'];
        }
        if ($industry = Category::instance()->get(['type' => 'sector', 'id' => $params['industry']])) {
            $params['industry'] = $industry['name'];
        }
        $result = false;
        Db::startTrans();
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                $row->validateFailException()->validate($validate);
            }
            $result = $row->allowField(true)->save($params);
            // todo 修改时并更新User表信息
            if ($user = \app\common\model\User::instance()->get(['id' => $params['user_id']])) {
                $user->allowField(true)->save(['nickname' => $params['nickname']]);
            }
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if (false === $result) {
            $this->error(__('No rows were updated'));
        }
        $this->success();
    }

    /**
     * 资质列表
     * */
    public function list()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $condition = [];
            if ($ids = $this->request->request('ids')) {
                $condition['user_id'] = $this->model->get(['id' => $ids])['user_id'];
            }
            $list = UserQualifications::instance()
                ->where($where)
                ->where($condition)
                ->order('createtime DESC')
                ->paginate($limit);

            foreach ($list as $row) {
            }

            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 添加资质
     * */
    public function qualifications($ids = null)
    {
        if (!$this->request->isAjax()) {
            $this->assign([
                'user_id' => $this->model->get(['id' => $ids])['user_id']
            ]);
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $file = explode('/', $params['path']);
        $params['path_file_names'] = end($file);
        if ($qualifications = Category::instance()->get(['type' => 'qualifications', 'id' => $params['name']])) {
            $params['name'] = $qualifications['name'];
        }
        $result = false;
        Db::startTrans();
        try {
            $result = UserQualifications::instance()->allowField(true)->save($params);
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if (false === $result) {
            $this->error(__('No rows were updated'));
        }
        $this->success();
    }

    /**
     * 编辑资质
     */
    public function updates($ids = null)
    {
        $row = UserQualifications::instance()->get(['id' => $ids]);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        if (!$this->request->isAjax()) {
            $row['cid'] = '';
            if ($qualifications = \app\admin\model\Category::get(['name' => $row['name'], 'type' => 'qualifications'])) {
                $row['cid'] = $qualifications['id'];
            }
            $this->assign([
                'row' => $row,
                'id' => $ids
            ]);
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $file = explode('/', $params['path']);
        $params['path_file_names'] = end($file);
        if ($qualifications = Category::instance()->get(['type' => 'qualifications', 'id' => $params['name']])) {
            $params['name'] = $qualifications['name'];
        }
        $result = false;
        Db::startTrans();
        try {
            $result = $row->allowField(true)->save($params);
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if (false === $result) {
            $this->error(__('No rows were updated'));
        }
        $this->success();
    }

    /**
     * 删除资质
     * */
    public function deletes($ids = null)
    {
        if (false === $this->request->isPost()) {
            $this->error(__("Invalid parameters"));
        }
        $ids = $ids ?: $this->request->post("ids");
        if (empty($ids)) {
            $this->error(__('Parameter %s can not be empty', 'ids'));
        }
        $pk = UserQualifications::instance()->getPk();
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            UserQualifications::instance()->where($this->dataLimitField, 'in', $adminIds);
        }
        $list = UserQualifications::instance()->where($pk, 'in', $ids)->select();

        $count = 0;
        Db::startTrans();
        try {
            foreach ($list as $item) {
                $count += $item->delete();
            }
            Db::commit();
        } catch (PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($count) {
            $this->success();
        }
        $this->error(__('No rows were deleted'));
    }
}
